import { defineStore } from 'pinia'
import { ref } from 'vue'
import { pluginApi } from '@/api/plugin'
import type { Plugin } from '@/types/plugin'

/**
 * 插件接口
 */
export interface Plugin {
  id: string
  name: string
  version: string
  compatibleVersion: string
  developer: string
  description: string
  isActive: boolean
  contact?: string
  dependencies?: string[]
  extensionPoints?: string[]
}

export const usePluginStore = defineStore('plugin', () => {
  // 插件列表
  const plugins = ref<Plugin[]>([])
  // 数据加载状态
  const loading = ref(false)
  // 错误信息
  const error = ref<string | null>(null)
  // 是否已初始化
  const initialized = ref(false)
  
  // 加载插件数据
  const fetchPlugins = async () => {
    // 如果已经有数据且已初始化，直接返回
    if (plugins.value.length > 0 && initialized.value) {
      console.log('使用缓存的插件数据')
      return plugins.value
    }
    
    loading.value = true
    error.value = null
    
    try {
      console.log('从服务器获取插件数据')
      plugins.value = await pluginApi.getPlugins()
      initialized.value = true
      return plugins.value
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err)
      console.error('获取插件数据失败:', errorMessage)
      error.value = `获取插件数据失败: ${errorMessage}`
      throw new Error(`获取插件数据失败: ${errorMessage}`)
    } finally {
      loading.value = false
    }
  }
  
  // 重置状态（用于登出时清理）
  const reset = () => {
    plugins.value = []
    loading.value = false
    error.value = null
    initialized.value = false
  }
  
  // 切换插件状态
  const togglePluginStatus = async (pluginId: string, enable: boolean) => {
    try {
      loading.value = true
      const updatedPlugin = await pluginApi.togglePluginStatus(pluginId, enable)
      const plugin = plugins.value.find((p: Plugin) => p.id === pluginId)
      if (plugin) {
        plugin.isActive = enable
      }
      return updatedPlugin
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err)
      console.error(`切换插件状态失败:`, errorMessage)
      throw new Error(`切换插件状态失败: ${errorMessage}`)
    } finally {
      loading.value = false
    }
  }
  
  // 删除插件
  const deletePlugin = async (pluginId: string) => {
    try {
      loading.value = true
      await pluginApi.deletePlugin(pluginId)
      const index = plugins.value.findIndex((p: Plugin) => p.id === pluginId)
      if (index !== -1) {
        plugins.value.splice(index, 1)
      }
      return true
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err)
      console.error(`删除插件失败:`, errorMessage)
      throw new Error(`删除插件失败: ${errorMessage}`)
    } finally {
      loading.value = false
    }
  }
  
  // 添加插件
  const addPlugin = async (plugin: Plugin) => {
    try {
      loading.value = true
      const newPlugin = await pluginApi.addPlugin(plugin)
      plugins.value.push(newPlugin)
      return newPlugin
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err)
      console.error(`添加插件失败:`, errorMessage)
      throw new Error(`添加插件失败: ${errorMessage}`)
    } finally {
      loading.value = false
    }
  }
  
  return {
    plugins,
    loading,
    error,
    initialized,
    fetchPlugins,
    togglePluginStatus,
    deletePlugin,
    addPlugin,
    reset
  }
}) 